<template>
  <div class="tab-menus-container" ref="tabMenusWrap">
    <div :style="wrapWidth" class="tab-menus-wrap">
      <div 
        :class="selectKey === item.key ? 'tab-menu-item tab-menu-item-active' : 'tab-menu-item'" 
        @click="selectTab(item.key, index)"
        v-for="(item, index) in menus" 
        :key="index">
        <span>{{ item.name }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'tab-menus',
  props: {
    menus: { type: Array },
    category: { type: String, default: 'recommend' }
  },
  data() {
    return {
      selectKey: this.category,
      timer: null,
    }
  },
  created() {
    // this.selectKey = this.menus[0].key;
  },
  methods: {
    selectTab(key, index) {
      clearInterval(this.timer)
      this.selectKey = key;
      let _scrollLeft;
      const originScrollLeft = this.$refs.tabMenusWrap.scrollLeft;
      const _clientWidth = this.$refs.tabMenusWrap.clientWidth;
      const _itemWidth = _clientWidth / 5;

      if(index < 4) {
        _scrollLeft = 0;
      } else if(index > this.menus.length - 4) {
        _scrollLeft = _itemWidth * this.menus.length - 5;
      } else {
        _scrollLeft = _itemWidth * (index - 2)
      }

      const step = (_scrollLeft - originScrollLeft) / 10;
      this.timer = setInterval(() => {
        if((this.$refs.tabMenusWrap.scrollLeft + step > _scrollLeft && step > 0) ||
          (this.$refs.tabMenusWrap.scrollLeft + step < _scrollLeft && step < 0)
        ) {
          this.$refs.tabMenusWrap.scrollLeft = _scrollLeft;
          clearInterval(this.timer)
        } else {
          this.$refs.tabMenusWrap.scrollLeft = this.$refs.tabMenusWrap.scrollLeft + step;
        }
      }, 20);

      this.$emit('handleClickCategory', key)
    }
  },
  beforeUnmount() {
    clearInterval(this.timer)
  },
  computed: {
    wrapWidth() {
      return `width: ${this.menus.length * 20}vw`;
    }
  }
}
</script>

<style lang="less" scoped>
@import '~theme/flex.less';
.tab-menus-container {
  width: 100vw;
  border-bottom: 1px solid #eeeeee;
  overflow: scroll;
  transition: all .2s ease-in-out;
}

.tab-menus-wrap {
  width: 240vw;
  #myFlex.rcs();
  white-space: nowrap;

  .tab-menu-item {
    width: 20vw;
    height: 12vw;
    #myFlex.rcc();
    font-size: 1.3rem;
    position: relative;
    overflow: hidden;
  }

  .tab-menu-item-active {
    font-size: 1.5rem;
    color: #ff0000;
  }
}
</style>